<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
          <!--          <el-form-item label="健身房id" prop="gymId">
            <el-input v-model="queryParams.gymId" placeholder="请输入健身房id" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--       <el-form-item label="会员卡编号" prop="cardId">
            <el-input v-model="queryParams.cardId" placeholder="请输入会员卡编号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="选择会员卡" prop="cardId">
            <el-select v-model="queryParams.cardId" placeholder="请选择" filterable clearable>
              <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择会员" prop="memberId">
            <!-- :disabled='dialog.isdis' -->
            <el-select v-model="queryParams.memberId" placeholder="请选择" filterable clearable>
              <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
          <!--        <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="订单数量" prop="orderNum">
            <el-input v-model="queryParams.orderNum" placeholder="请输入订单数量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="订单价格" prop="orderPrice">
            <el-input v-model="queryParams.orderPrice" placeholder="请输入订单价格" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="三方订单编号" prop="thirdPartyOrderNo">
            <el-input v-model="queryParams.thirdPartyOrderNo" placeholder="请输入三方订单编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付金额" prop="amount">
            <el-input v-model="queryParams.amount" placeholder="请输入支付金额" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付时间" prop="payTime">
            <el-date-picker clearable
              v-model="queryParams.payTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择支付时间"
            />
          </el-form-item> -->
          <!--          <el-form-item label="有效期至" prop="indateTime">
            <el-date-picker clearable
              v-model="queryParams.indateTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择有效期至"
            />
          </el-form-item> -->
          <!--          <el-form-item label="办卡日期" prop="registerCardTime">
            <el-date-picker clearable
              v-model="queryParams.registerCardTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择办卡日期"
            />
          </el-form-item> -->
          <!--          <el-form-item label="销售人，人员信息的主键id" prop="gymUserId">
            <el-input v-model="queryParams.gymUserId" placeholder="请输入销售人，人员信息的主键id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付方式" prop="patternPayment">
            <el-input v-model="queryParams.patternPayment" placeholder="请输入支付方式" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['primary:order:add']">新增</el-button>
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:order:edit']">修改</el-button>
          </el-col> -->
          <!--      <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:order:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['primary:order:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="订单id" align="center" prop="id" v-if="true" />
        <el-table-column label="健身房id" align="center" prop="gymId" /> -->
        <el-table-column label="会员姓名" align="center" prop="memberName" />
        <el-table-column label="会员卡编号" align="center" prop="cardName" />
        <!-- <el-table-column label="订单编号" align="center" prop="orderNo" /> -->
        <el-table-column label="销售类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_market_type" :value="scope.row.marketType" />
          </template>
        </el-table-column>
        <el-table-column label="订单数量" align="center" prop="orderNum" />
        <el-table-column label="支付金额" align="center" prop="amount" />
        <el-table-column label="订单价格" align="center" prop="orderPrice" />
        <!-- <el-table-column label="三方订单编号" align="center" prop="thirdPartyOrderNo" /> -->

        <!--        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!--       <el-table-column label="有效期至" align="center" prop="indateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.indateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="订单状态" align="center">
          <template #default="scope">
            <dict-tag :options="g_order_type" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="办卡日期" align="center" prop="registerCardTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerCardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="销售人" align="center" prop="nickName" />

        <el-table-column label="支付方式" align="center">
          <template #default="scope">
            <dict-tag :options="g_pay_type" :value="scope.row.patternPayment" />
          </template>
        </el-table-column>

        <!--     <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
          <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:order:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:order:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="560px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="110px">
        <!--    <el-form-item label="健身房id" prop="gymId">
          <el-input v-model="form.gymId" placeholder="请输入健身房id" type="number" :min="0" />
        </el-form-item> -->
        <!--      <el-form-item label="会员卡编号" prop="cardId">
          <el-input v-model="form.cardId" placeholder="请输入会员卡编号" />
        </el-form-item> -->
        <el-form-item label="选择会员卡" prop="cardId">
          <el-select v-model="form.cardId" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择会员" prop="memberId">
          <el-select v-model="form.memberId" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <!--       <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item> -->
        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单数量" type="number" :min="0" />
        </el-form-item>
        <!--        <el-form-item label="订单价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单价格(元)" type="number" :min="0" />
        </el-form-item> -->
        <!--       <el-form-item label="三方订单编号" prop="thirdPartyOrderNo">
          <el-input v-model="form.thirdPartyOrderNo" placeholder="请输入三方订单编号" />
        </el-form-item> -->
        <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入支付金额" type="number" :min="0" />
        </el-form-item>
        <!--        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="有效期至" prop="indateTime">
          <el-date-picker clearable v-model="form.indateTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期至">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="办卡日期" prop="registerCardTime">
          <el-date-picker clearable v-model="form.registerCardTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择办卡日期">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="销售人id" prop="gymUserId">
          <el-input v-model="form.gymUserId" placeholder="请输入销售人，人员信息的主键id" />
        </el-form-item> -->
        <el-form-item label="跟进教练" prop="userId">
          <span>{{form.userId}}</span>
          <el-select v-model="form.userId" placeholder="请选择" :disabled="dialog.isdis" filterable clearable>
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售类型" prop="marketType">
          <el-select v-model="form.marketType" placeholder="请选择">
            <el-option v-for="item in g_market_type" :key="item.value" :label="item.label" :value="item.value.toString()" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择">
            <el-option v-for="dict in g_order_type" :key="dict.value" :label="dict.label" :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="patternPayment">
          <el-select v-model="form.patternPayment" placeholder="请选择">
            <el-option v-for="dict in g_pay_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/primary/order';
import { listClubCard } from '@/api/primary/clubCard';
import { ClubCardForm } from '@/api/primary/clubCard/types';
import { listMember } from '@/api/primary/member';
import { OrderVO, OrderQuery, OrderForm } from '@/api/primary/order/types';
import { listRole } from "@/api/system/role";
import { listCoach } from '@/api/primary/coach';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { g_order_type, g_pay_type, g_market_type } = toRefs<any>(proxy?.useDict("g_order_type", "g_pay_type", "g_market_type"));
const memberList = ref<any>([]);
let clubCardLista = ref<any>([]);
const coachList = ref<any>([]);
const roleCan = ref<any>();
const roleList = ref<any>();
const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  isdis: 0
});
const initFormData : OrderForm = {
  id: undefined,
  gymId: undefined,
  memberType: undefined,
  userId: undefined,
  memberId: undefined,
  cardId: undefined,
  orderNo: undefined,
  orderNum: undefined,
  orderPrice: undefined,
  thirdPartyOrderNo: undefined,
  amount: undefined,
  payTime: undefined,
  indateTime: undefined,
  orderStatus: undefined,
  registerCardTime: undefined,
  gymUserId: undefined,
  marketType: undefined,
  patternPayment: undefined
}
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberType: undefined,
    memberId: undefined,
    gymId: undefined,
    userId: undefined,
    cardId: undefined,
    orderNo: undefined,
    orderNum: undefined,
    orderPrice: undefined,
    thirdPartyOrderNo: undefined,
    amount: undefined,
    payTime: undefined,
    indateTime: undefined,
    orderStatus: undefined,
    registerCardTime: undefined,
    gymUserId: undefined,
    marketType: undefined,
    patternPayment: undefined,
    params: {
    }
  },
  rules: {
    // id: [
    //   { required: true, message: "订单id不能为空", trigger: "change" }
    // ],
    userId: [
      { required: true, message: "跟进教练不能为空", trigger: "change" }
    ],
    cardId: [
      { required: true, message: "会员卡编号不能为空", trigger: "change" }
    ],
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "change" }
    ],
    orderNum: [
      { required: true, message: "订单数量不能为空", trigger: "change" }
    ],
    orderPrice: [
      { required: true, message: "订单价格不能为空", trigger: "change" }
    ],
    // thirdPartyOrderNo: [
    //   { required: true, message: "三方订单编号不能为空", trigger: "change" }
    // ],
    amount: [
      { required: true, message: "支付金额不能为空", trigger: "change" }
    ],
    payTime: [
      { required: true, message: "支付时间不能为空", trigger: "change" }
    ],
    indateTime: [
      { required: true, message: "有效期至不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
    registerCardTime: [
      { required: true, message: "办卡日期不能为空", trigger: "blur" }
    ],
    gymUserId: [
      { required: true, message: "销售人不能为空", trigger: "change" }
    ],
    marketType: [
      { required: true, message: "销售类型不能为空", trigger: "change" }
    ],
    patternPayment: [
      { required: true, message: "支付方式", trigger: "change" }
    ]
  }
});
const { queryParams, form, rules } = toRefs(data);
/** 查询会员卡信息列表 */
const getListcard = async () => {
  const res = await listClubCard(queryParams.value);
  clubCardLista = res.rows;
  console.log(clubCardLista, '会员卡列表')
}

/** 查询会员信息列表 */
const getListvip = async () => {
  queryParams.value.memberType = 0
  const res = await listMember(queryParams.value);
  memberList.value = res.rows;
  console.log(memberList.value, '正式会员表')
  queryParams.value.memberType = undefined
}
// 教练表
const getListb = async () => {
  const res = await listCoach(queryParams.value);
  coachList.value = res.rows;
  console.log(coachList.value, '教练信息表')
}
// const getListb = () => {
//   // queryParams.value.startDate=''
//   // queryParams.value.endDate=''

//   listRole(proxy?.addDateRange(queryParams.value)).then(res => {
//     roleList.value = res.rows
//     roleCan.value = roleList.value.find(item => item.roleName === '健身教练');
//     console.log(roleCan.value.roleId, '健身教练id')
//     getListc()
//   })
// }
/** 查询订单信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection : OrderVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.isdis = false
  dialog.visible = true;
  dialog.title = "添加订单信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row ?: OrderVO) => {
  reset();
  dialog.isdis = true
  const _id = row?.id || ids.value[0]
  const res = await getOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改订单信息";
}

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid : boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrder(form.value).finally(() => buttonLoading.value = false);
        proxy?.$modal.msgSuccess("修改成功");
      } else {
        await addOrder(form.value).finally(() => buttonLoading.value = false);
        proxy?.$modal.msgSuccess("添加成功");
        queryParams.value.cardId = ''
        queryParams.value.memberId = ''
      }

      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row ?: OrderVO) => {
  const _ids = row?.id || ids.value;
  let name = row.cardId
  await proxy?.$modal.confirm('是否确认删除订单信息编号为"' + name + '"的数据项？').finally(() => loading.value = false);
  await delOrder(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('primary/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  queryParams.value.pageNum=undefined
  queryParams.value.pageSize=undefined
  getListb()
  getListvip()
  getListcard()
  queryParams.value.pageNum=1
  queryParams.value.pageSize=10
  getList();

});
</script>
